from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from goods.models import SKU, GoodsCategory, SPU
from meiduo_admin.serializers.skus import SKUSerialzier, SKUCategorieSerializer, SPUSpecificationOptionSerializer, \
    SPecificationOptionSerializer
from meiduo_admin.utils import PageNum


class SKUView(ModelViewSet):
    permission_classes = [IsAdminUser]
    queryset = SKU.objects.all()
    serializer_class = SKUSerialzier
    pagination_class = PageNum

    @action(methods=["get"], detail=False)
    def categories(self, request):
        data = GoodsCategory.objects.filter(subs__id=None)
        ser = SKUCategorieSerializer(data, many=True)

        return Response(ser.data)

    def specs(self, request, pk):
        spu = SPU.objects.get(id=pk)
        data = spu.specs.all()
        ser = SPUSpecificationOptionSerializer(instance=data, many=True)
        return Response(ser.data)

    def get_queryset(self):
        if self.request.query_params.get("keyword") == "" or self.request.query_params.get("keyword") is None:
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=self.request.query_params.get("keyword"))
